package com.cssw.fyzb.core.mao.video;

import com.cssw.fyzb.core.model.mos.UserVideoMo;
import com.cssw.fyzb.core.mongo.MongoClient;
import com.cssw.fyzb.core.util.DocUtil;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;

/**
 * @author YangYiQun
 */
@Component
public class UserVideoMaoImpl implements UserVideoMao {

    @Autowired
    private MongoClient mongoClient;

    @Override
    public UserVideoMo findByVideoId(Long videoId) {
        Document doc = mongoClient.getCollection("user_video")
                .find(new Document("videoId", videoId))
                .first();
        return DocUtil.decoce(doc, UserVideoMo.class);
    }

    @Override
    public void createIfNull(Long videoId) {
        UserVideoMo userVideoMo = findByVideoId(videoId);
        if (null == userVideoMo){
            userVideoMo = new UserVideoMo();
            userVideoMo.setVideoId(videoId);
            userVideoMo.setLikes(Collections.emptyList());
            mongoClient.getCollection("user_video").insertOne(DocUtil.encode(userVideoMo));
        } else if (null == userVideoMo.getLikes()){
            userVideoMo.setLikes(Collections.emptyList());
            mongoClient.getCollection("user_video").updateOne(
                    new Document("videoId", videoId), DocUtil.encode(userVideoMo));
        }
    }

    @Override
    public void like(Long videoId, Long userId) {
        createIfNull(videoId);

        mongoClient.getCollection("user_video").updateOne(
                new Document("videoId", videoId),
                new Document("$addToSet", new Document("likes", userId))
        );
    }

    @Override
    public boolean existsLike(Long videoId, Long userId) {
        UserVideoMo userVideoMo = findByVideoId(videoId);
        if (null == userVideoMo || userVideoMo.getLikes() == null){
            return false;
        }
        return userVideoMo.getLikes().contains(userId);
        /*Document query = new Document()
                .append("videoId", videoId);
                //.append("likes.userId", userId);

        Document doc = mongoClient.getCollection("user_video")
                .find(query)
                .first();
        if (null != doc ){

        }
        return doc != null;*/
    }

    @Override
    public void cancelLike(Long videoId, Long userId) {
        mongoClient.getCollection("user_video").updateOne(
                new Document("videoId", videoId),
                new Document("$pull", new Document("likes", userId))
        );
    }
}
